import 'package:flutter/material.dart';

/// 在子widget中获取state的四种方法
class GetStateObjectRoute extends StatefulWidget {
  const GetStateObjectRoute({Key? key}) : super(key: key);

  @override
  State<GetStateObjectRoute> createState() => _GetStateObjectRouteState();
}

class _GetStateObjectRouteState extends State<GetStateObjectRoute> {
  // 4.1 定义一个globalKey, 由于GlobalKey要保持全局唯一性，我们使用静态变量存储
  static GlobalKey<ScaffoldState> _globalKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _globalKey, //设置key
      appBar: AppBar(
        title: Text("子树中获取State对象"),
      ),
      body: Center(
        child: Column(
          children: [
            Text(
                "BuildContext类的一个实例，表示当前 widget 在 widget 树中的上下文，每一个 widget 都会对应一个 context 对象"),
            Text("打开drawer需要父层state对象，例如ScaffoldState？"),
            // 1. 获取 StatefulWidget 的状态的方法是通用的，我们并不能在语法层面指定 StatefulWidget 的状态是否私有 ???
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  // 查找父级最近的Scaffold对应的ScaffoldState对象
                  ScaffoldState state =
                      context.findAncestorStateOfType<ScaffoldState>()!;
                  // 打开抽屉菜单
                  state.openDrawer();
                },
                child: Text('打开抽屉菜单1：context.findAncestorStateOfType'),
              );
            }),

            // 2. 直接通过of静态方法来获取ScaffoldState, 私有化？？？
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  ScaffoldState state = Scaffold.of(context);
                  // 打开抽屉菜单
                  state.openDrawer();
                },
                child: Text('打开抽屉菜单2: Scaffold.of(context)'),
              );
            }),

            // 3. 显示 snack bar
            Builder(builder: (context) {
              return ElevatedButton(
                onPressed: () {
                  ScaffoldMessengerState state = ScaffoldMessenger.of(context);
                  state.showSnackBar(
                    SnackBar(
                        content:
                            Text("我是SnackBar: ScaffoldMessenger.of(context)")),
                  );
                },
                child: Text('显示SnackBar'),
              );
            }),
            ElevatedButton(
              onPressed: () {
                print("_globalKey.currentState ${_globalKey.currentState}");
                _globalKey.currentState?.openDrawer();
              },
              child: Text('打开抽屉菜单3: _globalKey.currentState'),
            )
          ],
        ),
      ),
      drawer: Drawer(),
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: GetStateObjectRoute(),
  ));
}
